package service

import (
	"context"
	"database/sql"

	"gitee.com/WisdomClassroom/ClassStruct/glb"
	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/models"
	"gitee.com/WisdomClassroom/core/protobufs/v1/pb"
	"google.golang.org/grpc/metadata"
	"gorm.io/gorm"
)

func (s *Service) UpdateClass(ctx context.Context, request *pb.UpdateClassRequest) (*pb.UpdateClassResponse, error) {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		glb.Logger.Error("no metadata")
	}
	token, err := core.UnpackTokenFromMetadata(md)
	if err != nil {
		return &pb.UpdateClassResponse{Status: &pb.ResponseStatus{
			Code: core.ResponseStatusCodeNotAuth, Message: err.Error(),
		}}, nil
	}

	if !token.IsManager && token.Type != core.UserTypeTeacher {
		return &pb.UpdateClassResponse{Status: &pb.ResponseStatus{
			Code:    core.ResponseStatusCodeNotAuth,
			Message: "用户没有权限",
		}}, nil
	}

	class := &models.ClassModel{UUID: request.GetUUID()}
	err = glb.DB.Select("uuid").Take(class).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return &pb.UpdateClassResponse{Status: &pb.ResponseStatus{
				Code:    core.ResponseStatusCodeOtherError,
				Message: "班级不存在",
			}}, nil
		}
		glb.Logger.Error(err.Error())
		return updateClassRespSvrErr, nil
	}

	class.Name = sql.NullString{String: request.GetName(), Valid: true}
	class.Description = sql.NullString{String: request.GetDescription(), Valid: true}
	err = glb.DB.Model(class).Updates(class).Error
	if err != nil {
		glb.Logger.Error(err.Error())
		return updateClassRespSvrErr, nil
	}

	return &pb.UpdateClassResponse{
		Status: &pb.ResponseStatus{Code: core.ResponseStatusCodeSuccess},
	}, nil
}
